package com.yz.jdd.webview;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.net.wifi.ScanResult;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.provider.Settings;

import androidx.core.content.FileProvider;

import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;

import com.alipay.sdk.app.AuthTask;
import com.alipay.sdk.app.PayTask;
import com.gyf.barlibrary.ImmersionBar;

import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.github.lzyzsd.jsbridge.BridgeHandler;
import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.github.lzyzsd.jsbridge.BridgeWebViewClient;
import com.github.lzyzsd.jsbridge.CallBackFunction;
import com.github.lzyzsd.jsbridge.DefaultHandler;
import com.google.gson.JsonParser;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.trello.rxlifecycle.ActivityEvent;
import com.google.gson.JsonObject;
import com.yunzong.permissions.OnPermission;
import com.yunzong.permissions.Permission;
import com.yunzong.permissions.XXPermissions;
import com.yunzong.wifi.WifiSupport;
import com.yunzong.wifi.netconfig.SmartConfig;
import com.yz.jdd.R;
import com.yz.jdd.base.activity.BaseActivity;
import com.yz.jdd.base.activity.PhotoViewActivity;
import com.yz.jdd.base.entity.Image;
import com.yz.jdd.base.entity.Response_Base;
import com.yz.jdd.base.event.Events;
import com.yz.jdd.base.event.RxBus;
import com.yz.jdd.base.utils.AppUtils;
import com.yz.jdd.base.utils.AuthResult;
import com.yz.jdd.base.utils.FileUtils;
import com.yz.jdd.base.utils.ProviderUtil;
import com.yz.jdd.base.utils.StringUtil;
import com.yz.jdd.module.help.HelpActivity;
import com.yz.jdd.module.launch.model.AppVersion;
import com.yz.jdd.module.scan.view.ScanActivity;
import com.yz.jdd.module.upgrade.DownLoadDialogActivity;
import com.yz.jdd.network.ApiCallback;
import com.yz.jdd.base.utils.BaseConfigs;
import com.yz.jdd.base.utils.Constants;
import com.yz.jdd.base.utils.GsonUtils;
import com.yz.jdd.base.utils.LogUtils;
import com.yz.jdd.base.utils.PreferencesUtils;
import com.yz.jdd.module.login.view.LoginActivity;
import com.yz.jdd.network.MySubscriber;
import com.yz.jdd.network.NetWorkRequset;
import com.yz.jdd.network.response.Response_upgrade;
import com.yz.jdd.photo.entity.Compress;
import com.yz.jdd.photo.entity.Crop;
import com.yz.jdd.photo.entity.MaxSize;
import com.yz.jdd.photo.entity.Photo;
import com.yz.jdd.photo.app.TakePhoto;
import com.yz.jdd.photo.app.TakePhotoImpl;
import com.yz.jdd.photo.compress.CompressOptions;
import com.yz.jdd.photo.model.CropOptions;
import com.yz.jdd.photo.model.InvokeParam;
import com.yz.jdd.photo.model.LubanOptions;
import com.yz.jdd.photo.model.TContextWrap;
import com.yz.jdd.photo.model.TImage;
import com.yz.jdd.photo.model.TResult;
import com.yz.jdd.photo.model.Upload;
import com.yz.jdd.photo.permission.InvokeListener;
import com.yz.jdd.photo.permission.PermissionManager;
import com.yz.jdd.photo.permission.TakePhotoInvocationHandler;
import com.yz.jdd.photo.utils.PhotoUtils;
import com.yz.jdd.photo.utils.TConstant;
import com.yz.jdd.photo.utils.TImageFiles;
import com.yz.jdd.photo.utils.TUtils;
import com.yz.jdd.voice.OrderVoice;
import com.yz.jdd.voice.SpeechUtilOffline;
import com.yz.jdd.webview.download.DataCleanManager;
import com.yz.jdd.webview.download.FetchUtil;
import com.yz.jdd.webview.download.H5DownFileUtils;
import com.yz.jdd.webview.entity.PayResult;
import com.yz.jdd.webview.entity.UserInfo;
import com.yz.jdd.webview.net.H5Subscription;
import com.yz.jdd.widget.PublicDialog;
import com.yz.jdd.widget.TopDialog;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import rx.functions.Action1;

import static android.os.Environment.DIRECTORY_PICTURES;


/**
 * 项目名称：Maneki
 * 创建人：zx
 * 创建时间：2017/1/11-下午2:36
 * h5与java交互
 */

public class H5BridgeOtherActivity extends BaseActivity implements TakePhoto.TakeResultListener, InvokeListener {
    public static final String TAG = "lkf";
    private BridgeWebView webview; //webview
    private LinearLayout errorLayout;
    private Intent intent;
    private String main_url = "";//跳转到该页面的url 由上一个页面返回
    private List<String> apiQueue = new ArrayList<String>();
    private TakePhoto takePhoto;
    private CallBackFunction takePictureCallBackFunction;
    private CallBackFunction selectPictureCallBackFunction;
    private CallBackFunction photoviewCallBackFunction;
    private CallBackFunction uploadPictureCallBackFunction;
    private CallBackFunction savePictureCallBackFunction;
    private CallBackFunction scanCallBackFunction;
    private CallBackFunction authV2CallBackFunction;
    private CallBackFunction payV2CallBackFunction;
    private InvokeParam invokeParam;

    private static String apiName;

    private EditText editText;
    private Button button;

    LinearLayout loading_layout;
//    ImageView blinkImg;

    RelativeLayout top_bar;
    ImageView back;
    ImageView close_web;
    TextView title;
    TextView rightTextView;
    private boolean control;
    private boolean create;
    private static final int SDK_PAY_FLAG = 2;
    SmartConfig smartConfig;

    private MyRecriver myRecriver;
    private IntentFilter intentFilter;


    private String backUrl;
    private boolean videoFlag = false;
    private ValueCallback<Uri> mUploadMessage;
    private ValueCallback<Uri[]> mUploadCallbackAboveL;
    private final static int PHOTO_REQUEST = 100;
    private final static int VIDEO_REQUEST = 120;
    private Uri imageUri;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getTakePhoto().onCreate(savedInstanceState);
        super.onCreate(savedInstanceState);
        ImmersionBar.with(this)
                .reset()  //重置所以沉浸式参数
                .transparentStatusBar()  //透明状态栏，不写默认透明色
                .statusBarColor(R.color.color_ffffff)     //状态栏颜色，不写默认透明色
                .statusBarDarkFont(true, 0.01f)   //状态栏字体是深色，不写默认为亮色
                .flymeOSStatusBarFontColor(R.color.color_333333)  //修改flyme OS状态栏字体颜色
                .fitsSystemWindows(true)    //解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色
                .supportActionBar(false) //支持ActionBar使用
                .addTag("tag")  //给以上设置的参数打标记
                .getTag("tag")  //根据tag获得沉浸式参数
                .init();
        setContentView(R.layout.activity_h5bridgeweb);
        AndroidBug5497Workaround.assistActivity(this);
        init();

        myRecriver = new MyRecriver();
        intentFilter = new IntentFilter();
        intentFilter.addAction("updateH5Page");
        registerReceiver(myRecriver, intentFilter);
    }

    /**
     * 注册RxBus事件监听
     */
    void registerRxBusEvents() {
        RxBus.with(H5BridgeOtherActivity.this).setEvent(Events.EVENT_IMAGEPREVIEW_RESULT).setEndEvent(ActivityEvent.DESTROY).onNext(new Action1<Events<?>>() {
            @Override
            public void call(Events<?> events) {
                if (events != null) {
                    if (Events.EVENT_IMAGEPREVIEW_RESULT.equals(events.code)) {
                        Response_Base response_base = events.getContent();
                        if (response_base != null) {
                            HostJsScope.h5PostLocalCallBack(webview, response_base.getCode(), response_base.getMsg(), response_base.success(), "viewPicture", response_base, photoviewCallBackFunction);
                            if (photoviewCallBackFunction != null) {
                                photoviewCallBackFunction = null;
                            }
                        }
                    }
                }
            }
        }).create();
        /**
         * 上传图回调h5
         */
        RxBus.with(H5BridgeOtherActivity.this).setEvent(Events.EVENT_UPLOADPICTURE_RESULT).setEndEvent(ActivityEvent.DESTROY).onNext(new Action1<Events<?>>() {
            @Override
            public void call(Events<?> events) {
                if (events != null) {
                    if (Events.EVENT_UPLOADPICTURE_RESULT.equals(events.code)) {
                        String str = events.getContent();
                        LogUtils.d("str :: " + str);
                        if (!TextUtils.isEmpty(str)) {
                            try {
                                JsonObject returnData = new JsonParser().parse(str).getAsJsonObject();
                                if (returnData != null) {
                                    HostJsScope.h5PostLocalCallBack(webview, "0", "图片上传成功", true, "uploadPicture", returnData, uploadPictureCallBackFunction);
                                    if (uploadPictureCallBackFunction != null) {
                                        uploadPictureCallBackFunction = null;
                                    }
                                } else {
                                    HostJsScope.h5PostLocalCallBack(webview, "-1", "图片上传失败", false, "uploadPicture", str, uploadPictureCallBackFunction);
                                    if (uploadPictureCallBackFunction != null) {
                                        uploadPictureCallBackFunction = null;
                                    }
                                }
                            } catch (Exception e) {
                                HostJsScope.h5PostLocalCallBack(webview, "-1", "图片上传失败", false, "uploadPicture", str, uploadPictureCallBackFunction);
                                if (uploadPictureCallBackFunction != null) {
                                    uploadPictureCallBackFunction = null;
                                }
                            }
                        } else {
                            HostJsScope.h5PostLocalCallBack(webview, "-1", "图片格式不支持", false, "uploadPicture", str, uploadPictureCallBackFunction);
                            if (uploadPictureCallBackFunction != null) {
                                uploadPictureCallBackFunction = null;
                            }
                        }
                    }

                }
            }
        }).create();
    }

    // 多进程,广播接收消息
    class MyRecriver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String content = intent.getStringExtra("event");
            if (!StringUtil.isEmpty(content)) {
                if (Events.EVENT_VOICE_BROADCAT.equals(content)) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            webview.loadUrl("javascript:AppUtil.trigger(AppUtil.EVENTS.NEW_ORDER_EVENT);");
                        }
                    });
                }
            } else if (Events.EVENT_LOAD_URL.equals(content)) {
                dismissLoading();
                webview.loadUrl(main_url);
            }

        }
    }

    private void init() {
        String sessionId = getIntent().getStringExtra("sessionId");
        if (!PreferencesUtils.getString(H5BridgeOtherActivity.this, BaseConfigs.PREF_SESSIONID, "").equals(sessionId)) {
            if (!TextUtils.isEmpty(sessionId)) {
                PreferencesUtils.putString(H5BridgeOtherActivity.this, BaseConfigs.PREF_SESSIONID, sessionId);
            }
        }
        loading_layout = (LinearLayout) findViewById(R.id.loading_layout);
        String loading = getIntent().getStringExtra("loading");
        if (!TextUtils.isEmpty(loading)) {
            loading_layout.setVisibility(View.GONE);
        }

        editText = (EditText) findViewById(R.id.edittext);
        button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!TextUtils.isEmpty(editText.getText().toString())) {
                    webview.loadUrl(editText.getText().toString() + "?android=4.1&statusBarHeight=40");
                }
            }
        });
        top_bar = (RelativeLayout) findViewById(R.id.top_bar);
        top_bar.setBackgroundColor(Color.parseColor("#ffffff"));

        back = (ImageView) findViewById(R.id.back);
        back.setImageResource(R.mipmap.back_left_blue);
        //注册事件
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (control) {
                    Log.e("lkf", "control");
                    webview.loadUrl("javascript:AppUtil.trigger(AppUtil.EVENTS.BACK_EVENT);");
                } else {
                    if (webview.canGoBack()) {
                        Log.e("lkf", "canGoBack");
                        webview.goBack();
                    } else {
                        Log.e("lkf", "finish");
                        finish();
                    }
                }

            }
        });
        close_web = findViewById(R.id.close_web);
        close_web.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        title = (TextView) findViewById(R.id.title);
        title.setTextColor(Color.parseColor("#3a9afe"));
        rightTextView = (TextView) findViewById(R.id.right);
        rightTextView.setTextColor(Color.parseColor("#3a9afe"));

        rightTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                webview.loadUrl("javascript:AppUtil.trigger(AppUtil.EVENTS.OPTION_MENU_EVENT);");
            }
        });

        registerRxBusEvents();
        webview = (BridgeWebView) findViewById(R.id.webview);
        errorLayout = (LinearLayout) findViewById(R.id.error_layout);
        errorLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isErrorPage = false;

                webview.reload();
            }
        });
        intent = this.getIntent();
        main_url = intent.getStringExtra(Constants.H5_WEB_URL);
        backUrl = intent.getStringExtra("backUrl");
        String showTop = intent.getStringExtra("showTop");
        if (!TextUtils.isEmpty(showTop)) {
            top_bar.setVisibility(View.GONE);
        } else {
            top_bar.setVisibility(View.VISIBLE);
        }
        String titleStr = intent.getStringExtra("title");
        if (!TextUtils.isEmpty(titleStr)) {
            title.setText(titleStr);
        } else {
            top_bar.setVisibility(View.GONE);
        }
        String backgroundStr = intent.getStringExtra("background");
        if (!TextUtils.isEmpty(backgroundStr)) {
            top_bar.setBackgroundColor(Color.parseColor(backgroundStr));
        }
        String colorStr = intent.getStringExtra("color");
        if (!TextUtils.isEmpty(colorStr)) {
            title.setTextColor(Color.parseColor(colorStr));
        }
        initWebView();
    }

    private TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(H5BridgeOtherActivity.this, this));
        }
        return takePhoto;
    }

    @Override
    protected void onResume() {
        super.onResume();
        //界面被唤醒的时候调用
        if (create) {
            webview.loadUrl("javascript:AppUtil.trigger(AppUtil.EVENTS.RESUME_EVENT);");
        } else {
            create = true;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && !isErrorPage) {
            //返回键调用js方法
            if (control) {
                webview.loadUrl("javascript:AppUtil.trigger(AppUtil.EVENTS.BACK_EVENT);");
            } else {
                if (webview.canGoBack()) {
                    webview.goBack();
                } else {
                    finish();
                }
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        webview.reload();
    }

    private void initWebView() {

        //规则在定义请求接口的时候需要首先调用,apiQueue.add("getrequest"); 因为js会首先调用checkApi接口,检验Android本地方法是否存在
        apiQueue.add("takePicture");//拍照裁剪接口
        apiQueue.add("selectPicture");//选择图片裁剪接口
        apiQueue.add("viewPicture");//图片预览接口
        apiQueue.add("uploadPicture");//上传图片
        apiQueue.add("logout");//退出登录接口
        apiQueue.add("getUserInfo");//获取用户信息
        apiQueue.add("exitApp");//js调用客户端前台切换到后台运行
        apiQueue.add("sendHttpRequest"); //发送http请求
        apiQueue.add("dial");//拨打电话
        apiQueue.add("login");//跳转登录
        apiQueue.add("setTitle");//设置页面的标题栏，包括主标题，副标题以及标题菜单项
        apiQueue.add("setOptionMenu");//设置标题栏右边的按钮属性。该接口仅负责设置，需要额外调用showOptionMenu保证该按钮的显示
        apiQueue.add("showOptionMenu");//显示标题栏右边的按钮属性
        apiQueue.add("hideOptionMenu");//隐藏标题栏右边的按钮属性
        apiQueue.add("pushWindow");//用来打开一个新的页面，系统自带转场动画。
        //与location.href的区别，类同于PC浏览器的新开标签页，每个window都是一个新的标签页，因此原页面仅仅是被压到后台，状态始终保持，JS也会继续运行。
        apiQueue.add("popWindow");//popWindow用来关闭当前页面，自动返回到上一个
        apiQueue.add("setBackOption");
        apiQueue.add("openApp");//打开三方app
        apiQueue.add("testVoiceBroadcast");
        apiQueue.add("savePicture");
        apiQueue.add("scan");
        apiQueue.add("authV2");//调用支付宝授权
        apiQueue.add("tradePay");//支付宝支付
        apiQueue.add("getNearbyWIFI");//1.获取附近wifi
        apiQueue.add("startBroadcast");//2.开启广播
        apiQueue.add("stopBroadcast");//3.关闭广播
        apiQueue.add("getAppVersion");//获取当前app版本号
        apiQueue.add("upgradeApp");//更新app版本
        apiQueue.add("openDetectVoiceRight");//语音播报故障诊断
        apiQueue.add("updateNativePage");//发消息给本地页面
        apiQueue.add("setServerUrl");//设置服务地址
        apiQueue.add("removeH5Source");//删除H5资源
        apiQueue.add("resetAll");//重置所有
        apiQueue.add("downLoadH5Source");//下载H5资源
        apiQueue.add("hideSplash");//隐藏
        apiQueue.add("writeLogToApp");//写日志接口
        apiQueue.add("openWifi");
        apiQueue.add("shardBySystem");


        webview.setWebViewClient(new MyWebViewClient(webview));
        webview.setWebChromeClient(new MyWebChromeClient());
        webview.getSettings().setUseWideViewPort(true);
        webview.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);//适应内容大小
        webview.getSettings().setLoadWithOverviewMode(true);
        webview.getSettings().setJavaScriptEnabled(true);
        webview.getSettings().setAllowFileAccess(true);
        webview.getSettings().setAllowFileAccessFromFileURLs(true);
        webview.getSettings().setAllowContentAccess(true);
        webview.getSettings().setAllowUniversalAccessFromFileURLs(true);
        webview.getSettings().setDefaultTextEncodingName("UTF-8");
        webview.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        //极速云所需配置
        webview.getSettings().setDomStorageEnabled(true);
        webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);//支持js调用window.open方法
        webview.getSettings().setSupportMultipleWindows(false);// 设置允许开启多窗口
        String ua = webview.getSettings().getUserAgentString();
        webview.getSettings().setUserAgentString(ua + ";androidapp/cross-bmios" + ";webJSY/1.0.0");
        webview.getSettings().setDomStorageEnabled(true);
        webview.getSettings().setUseWideViewPort(true);
        webview.getSettings().setRenderPriority(WebSettings.RenderPriority.LOW);
        webview.getSettings().setTextSize(WebSettings.TextSize.NORMAL);
        webview.getSettings().setTextZoom(100);
        webview.loadUrl(main_url);

        //调用系统分享
        webview.registerHandler("shardBySystem", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                if (TextUtils.isEmpty(data)) {
                    return;
                }
                JsonObject jsonObject = HostJsScope.Json2JsonObject(data);
                String filePath = Environment.getExternalStoragePublicDirectory(DIRECTORY_PICTURES) + "" + "/yz" + System.currentTimeMillis() + ".jpg";
                File takeImageFile = new File(filePath);
                if (jsonObject != null && jsonObject.get("imageBase64Str") != null) {
                    String imageBase64Str = jsonObject.get("imageBase64Str").getAsString();
                    Log.e("lkf", imageBase64Str);
                    int index = imageBase64Str.indexOf(",");
                    String subStr = imageBase64Str.substring(index + 1);
                    Log.e("lkf", subStr);
                    try {
                        byte[] buffer = Base64.decode(subStr.getBytes(), Base64.DEFAULT);
                        FileOutputStream out = new FileOutputStream(takeImageFile);
                        out.write(buffer);
                        out.close();
                        Log.e("lkf", takeImageFile.length() + "");
                    } catch (Exception e) {
                        Log.e("lkf", e.toString());
                        e.printStackTrace();
                    }

                }

                Uri uri;
                if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) {
                    uri = Uri.fromFile(takeImageFile);
                } else {
                    //7.0 调用系统相机拍照不再允许使用Uri方式，应该替换为FileProvider,并且这样可以解决MIUI系统上拍照返回size为0的情况
                    uri = FileProvider.getUriForFile(H5BridgeOtherActivity.this, ProviderUtil.getFileProviderName(H5BridgeOtherActivity.this), takeImageFile);
                }
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_SEND);
                intent.putExtra(Intent.EXTRA_STREAM, uri);
                intent.setType("image/*");
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                startActivity(Intent.createChooser(intent, ""));
            }
        });

        //打开wifi
        webview.registerHandler("openWifi", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                Intent wifiSettingsIntent = new Intent("android.settings.WIFI_SETTINGS");
                startActivity(wifiSettingsIntent);
            }
        });
        //隐藏
        webview.registerHandler("hideSplash", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                loading_layout.setVisibility(View.GONE);
            }
        });
        webview.registerHandler("writeLogToApp", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                if (TextUtils.isEmpty(data))
                    return;
                JsonObject jsonObject = HostJsScope.Json2JsonObject(data);
                if (jsonObject != null && jsonObject.get("text") != null) {
                    String text = jsonObject.get("text").getAsString() + "";
                }
            }
        });

        //设置服务地址url，清除版本号，删除资源重启
        webview.registerHandler("setServerUrl", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                if (TextUtils.isEmpty(data))
                    return;
                JsonObject jsonObject = HostJsScope.Json2JsonObject(data);
                if (jsonObject != null && jsonObject.get("url") != null) {
                    String url = jsonObject.get("url").getAsString() + "";
                    if (!TextUtils.isEmpty(url)) {
                        DataCleanManager.cleanApplicationData(H5BridgeOtherActivity.this);
                        PreferencesUtils.putString(
                                H5BridgeOtherActivity.this, BaseConfigs.STRING_SERVER_URL, url);
                        PreferencesUtils.putString(
                                H5BridgeOtherActivity.this, BaseConfigs.STRING_GUID, "");
                        //删除资源
                        android.os.Process.killProcess(android.os.Process.myPid());
                    }
                }
            }
        });

        //删除h5资源，删除解压文件
        webview.registerHandler("removeH5Source", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                DataCleanManager.cleanApplicationData(H5BridgeOtherActivity.this);
                android.os.Process.killProcess(android.os.Process.myPid());

            }
        });

        //重置所有，删除data
        webview.registerHandler("resetAll", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                DataCleanManager.cleanApplicationData(H5BridgeOtherActivity.this);
                android.os.Process.killProcess(android.os.Process.myPid());
            }
        });


        //解压h5资源
        webview.registerHandler("downLoadH5Source", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                if (TextUtils.isEmpty(data))
                    return;
                JsonObject jsonObject = HostJsScope.Json2JsonObject(data);
                if (jsonObject != null && jsonObject.get("url") != null) {
                    String downLoadUrl = jsonObject.get("url").getAsString() + "";
                    if (!TextUtils.isEmpty(downLoadUrl)) {
                        FetchUtil.downLoadH5zip(downLoadUrl);
                    }
                }
            }
        });

        //获取附近wifi
        webview.registerHandler("getNearbyWIFI", new BridgeHandler() {
            @Override
            public void handler(String data, final CallBackFunction function) {
                XXPermissions.with(H5BridgeOtherActivity.this).permission(
                        Permission.ACCESS_COARSE_LOCATION,
                        Permission.ACCESS_FINE_LOCATION
                ).request(new OnPermission() {
                    @Override
                    public void hasPermission(List<String> granted, boolean isAll) {
                        if (isAll) {
                            dismissTopDialog();
                            if (WifiSupport.isOpenWifi(H5BridgeOtherActivity.this)) {
                                List<ScanResult> scanResults = WifiSupport.noSameName(WifiSupport.getWifiScanResult(H5BridgeOtherActivity.this));
                                if (scanResults != null) {
                                    List<String> wifiList = new ArrayList<>();
                                    for (ScanResult scanResult : scanResults) {
                                        wifiList.add(scanResult.SSID);
                                    }
                                    if (wifiList.size() > 0) {
                                        HostJsScope.h5PostLocalCallBack(webview, TConstant.CODE_SUCCESS,
                                                "", true, "getNearbyWIFI", wifiList, function);
                                    } else {
                                        HostJsScope.h5PostLocalCallBack(webview, TConstant.CODE_FAIL,
                                                "未取到wif信息", false, "getNearbyWIFI", null, function);
                                    }

                                }

                            } else {
                                //打开wifi
                                final PublicDialog publicDialog = new PublicDialog(H5BridgeOtherActivity.this);
                                publicDialog.setMessage("请先开启手机Wi-Fi功能");
                                publicDialog.setRightBtn("去开启",
                                        new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS)); //直接进入手机中的wifi网络设置界面
                                                publicDialog.dismiss();
                                            }
                                        });
                                publicDialog.show();
                            }

                        }

                    }

                    @Override
                    public void noPermission(List<String> denied, boolean quick) {
                        dismissTopDialog();
                        HostJsScope.h5PostLocalCallBack(webview, TConstant.CODE_FAIL,
                                "未开启wifi权限", false, "getNearbyWIFI", null, function);
                    }
                });
                if (!XXPermissions.isHasPermission(H5BridgeOtherActivity.this, Permission.ACCESS_COARSE_LOCATION, Permission.ACCESS_FINE_LOCATION)) {
                    showTopDialog("为了您能正常使用玛卡龙、快小盒相关功能，请向您申请【定位】功能以获取附近WIFI，完成配网工作，保证功能的正常使用！");
                }
            }
        });
        //开启广播
        webview.registerHandler("startBroadcast", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                if (TextUtils.isEmpty(data))
                    return;
                JsonObject jsonObject = HostJsScope.Json2JsonObject(data);
                if (jsonObject != null && jsonObject.get("content") != null) {

                    String contentString = jsonObject.get("content").getAsString();
                    if (!TextUtils.isEmpty(contentString)) {
                        JsonObject content = HostJsScope.Json2JsonObject(contentString);
                        String name = content.get("name").getAsString() + "";
                        String password = content.get("password").getAsString() + "";
                        if (smartConfig != null) {
                            smartConfig.stop();
                        }
                        smartConfig = new SmartConfig(H5BridgeOtherActivity.this);
                        smartConfig.start(name, password);
                    }
                }
            }
        });
        //关闭广播
        webview.registerHandler("stopBroadcast", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                if (smartConfig != null)
                    smartConfig.stop();
            }
        });

        //控制返回事件
        webview.registerHandler("setBackOption", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                JsonObject jsonObject = HostJsScope.Json2JsonObject(data);
                if (jsonObject != null && jsonObject.get("control") != null) {
                    control = jsonObject.get("control").getAsBoolean();
                }
            }
        });

        //跳转登录关闭其他页面
        webview.registerHandler("login", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                RxBus.getInstance().send(Events.EVENT_302CODE, "");
                Intent intent = new Intent(H5BridgeOtherActivity.this, LoginActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

                intent.putExtra("logout", "1");

                startActivity(intent);

            }
        });

        //发消息给本地页面
        webview.registerHandler("updateNativePage", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                LogUtils.i("ljm--- H5 other " + data);
                Intent intent = new Intent("updateNativePage");
                if (data.contains("newsPage")) {
                    //    RxBus.getInstance().send(Events.EVENT_BACKLOG_CHANGE, "");
                    intent.putExtra("page", "newsPage");
                    sendBroadcast(intent);
                } else if (data.contains("orderPage")) {
                    //发消息,刷新首页/列表数据
                    intent.putExtra("page", "orderPage");
                    sendBroadcast(intent);
                } else {
                    startActivity(new Intent(H5BridgeOtherActivity.this, HelpActivity.class));
                }
            }
        });

        webview.registerHandler("openDetectVoiceRight", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                Intent intent = new Intent(H5BridgeOtherActivity.this, HelpActivity.class);
                startActivity(intent);
            }
        });
        webview.registerHandler("openApp", new DefaultHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                if (TextUtils.isEmpty(data))
                    return;
                JsonObject jsonObject = HostJsScope.Json2JsonObject(data);
                if (jsonObject != null && jsonObject.get("url") != null) {
                    String url = jsonObject.get("url").getAsString() + "";
                    if (url.startsWith("alipays:") || url.startsWith("alipay")) {
                        try {
                            startActivity(new Intent("android.intent.action.VIEW", Uri.parse(url)));
                            HostJsScope.h5PostLocalCallBack(webview, "0", "", true, "openApp", "", function);
                        } catch (Exception e) {
                            HostJsScope.h5PostLocalCallBack(webview, "-1", "", false, "openApp", "", function);
                        }

                    }

                }

            }
        });

        //设置页面的标题栏，包括主标题，副标题以及标题菜单项:background：”#ff0000”,   //标题栏背景色 color：”#ffff00”//文字颜色;showClose :是否显示关闭
        webview.registerHandler("setTitle", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                if (TextUtils.isEmpty(data)) {
                    return;
                }

                JsonObject jsonObject = HostJsScope.Json2JsonObject(data);
                if (jsonObject != null && jsonObject.get("title") != null) {
                    String titleStr = jsonObject.get("title").getAsString() + "";
                    title.setText(titleStr);
                }
                if (jsonObject != null && jsonObject.get("background") != null) {
                    String colorStr = jsonObject.get("background").getAsString() + "";
                    top_bar.setBackgroundColor(Color.parseColor(colorStr));
                }
                if (jsonObject != null && jsonObject.get("color") != null) {
                    String titleColorStr = jsonObject.get("color").getAsString() + "";
                    title.setTextColor(Color.parseColor(titleColorStr));
                }
                if (jsonObject != null && jsonObject.get("showClose") != null) {
                    boolean showClose = jsonObject.get("showClose").getAsBoolean();
                    if (showClose) {
                        close_web.setVisibility(View.VISIBLE);
                    } else {
                        close_web.setVisibility(View.GONE);
                    }
                }
            }
        });

        //设置标题栏右边的按钮属性。该接口仅负责设置，需要额外调用showOptionMenu保证该按钮的显示,{title : '按钮',color : '#ff00ff00', // 必须以＃开始ARGB颜色值}
        webview.registerHandler("setOptionMenu", new BridgeHandler() {

            @Override
            public void handler(String data, CallBackFunction function) {
                if (TextUtils.isEmpty(data))
                    return;
                JsonObject jsonObject = HostJsScope.Json2JsonObject(data);
                if (jsonObject != null && jsonObject.get("title") != null) {
                    String rightBtnStr = jsonObject.get("title").getAsString() + "";
                    rightTextView.setText(rightBtnStr);
                }
                if (jsonObject != null && jsonObject.get("color") != null) {
                    String rightBtnColor = jsonObject.get("color").getAsString() + "";
                    rightTextView.setTextColor(Color.parseColor(rightBtnColor));
                }
            }
        });
        //显示标题栏右边的按钮属性
        webview.registerHandler("showOptionMenu", new BridgeHandler() {

            @Override
            public void handler(String data, CallBackFunction function) {
                rightTextView.setVisibility(View.VISIBLE);
            }
        });

        //隐藏标题栏右边的按钮属性
        webview.registerHandler("hideOptionMenu", new BridgeHandler() {

            @Override
            public void handler(String data, CallBackFunction function) {
                rightTextView.setVisibility(View.GONE);
            }
        });

        //测试语音
        webview.registerHandler("testVoiceBroadcast", new BridgeHandler() {

            @Override
            public void handler(String data, CallBackFunction function) {
                try {
                    JsonObject jsonObject = HostJsScope.Json2JsonObject(data);
                    if (jsonObject != null && jsonObject.get("text") != null) {
                        String text = jsonObject.get("text").getAsString() + "";

                        OrderVoice orderVoice = new OrderVoice();
                        orderVoice.setContent(text);
                        if (XXPermissions.isHasPermission(H5BridgeOtherActivity.this, Permission.READ_PHONE_STATE)) {
                            try {
                                LogUtils.e("=== SpeechUtilOffline play Content:" + orderVoice.getContent());
                                SpeechUtilOffline.getInstance(getApplicationContext()).play(orderVoice, SpeechUtilOffline.PLAY_MODE.QUEUED);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    OrderVoice orderVoice = new OrderVoice();
                    orderVoice.setContent("语音播报成功");
                    if (XXPermissions.isHasPermission(H5BridgeOtherActivity.this, Permission.READ_PHONE_STATE)) {
                        try {
                            LogUtils.e("=== SpeechUtilOffline play Content:" + orderVoice.getContent());
                            SpeechUtilOffline.getInstance(getApplicationContext()).play(orderVoice, SpeechUtilOffline.PLAY_MODE.QUEUED);
                        } catch (Exception e1) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });


        /**
         * //用来打开一个新的页面，系统自带转场动画。
         * 与location.href的区别，类同于PC浏览器的新开标签页，每个window都是一个新的标签页，
         * 因此原页面仅仅是被压到后台，状态始终保持，JS也会继续运行。
         * {
         url: 'https://m.taobao.com/',
         param: {
         title: {
         title: '标题’,
         background：”#ff0000”,   //标题栏背景色
         color：”#ffff00”         //标题栏前景色
         },
         showOptionMenu: false  //缺省  可不传，默认为false
         }
         */
        webview.registerHandler("pushWindow", new

                BridgeHandler() {

                    @Override
                    public void handler(String data, CallBackFunction function) {
                        LogUtils.e(data);
                        if (TextUtils.isEmpty(data))
                            return;
                        JsonObject jsonObject = HostJsScope.Json2JsonObject(data);
                        if (jsonObject != null) {
                            Intent intent = new Intent(H5BridgeOtherActivity.this, H5BridgeOtherActivity.class);

                            if (jsonObject.get("param") != null) {
                                JsonObject paramJsonObject = (JsonObject) jsonObject.get("param");
                                if (paramJsonObject != null) {
                                    try {
                                        JsonObject titleJsonObject = (JsonObject) paramJsonObject.get("title");
                                        if (titleJsonObject != null) {
                                            String titleStr = titleJsonObject.get("title").getAsString() + "";
                                            if (!TextUtils.isEmpty(titleStr))
                                                intent.putExtra("title", titleStr);
                                            String backgroundStr = titleJsonObject.get("background").getAsString() + "";
                                            if (!TextUtils.isEmpty(backgroundStr))
                                                intent.putExtra("background", backgroundStr);

                                            String colorStr = titleJsonObject.get("color").getAsString() + "";
                                            if (!TextUtils.isEmpty(colorStr))
                                                intent.putExtra("color", colorStr);
                                        } else {
                                            intent.putExtra("showTop", "showTop");
                                        }
                                    } catch (Exception e) {
                                        Log.e("lkf", e.toString());
                                        intent.putExtra("showTop", "showTop");
                                    }
                                }


                            }
                            String parme = "";
                            if (jsonObject.get("suffixParams") != null) {
                                parme = jsonObject.get("suffixParams").getAsString() + "";
                            }
                            if (jsonObject.get("url") != null) {
                                String openUrl = jsonObject.get("url").getAsString() + "";
                                if (!TextUtils.isEmpty(openUrl)) {
                                    String target = "";
                                    if (jsonObject.get("target") != null)
                                        target = jsonObject.get("target").getAsString() + "";

                                    if ("local".equals(target)) {
                                        openUrl = "file://" + H5DownFileUtils._UPZIP_FOLDERPATH + openUrl + "?s=" +
                                                PreferencesUtils.getString(H5BridgeOtherActivity.this, BaseConfigs.PREF_SESSIONID) +
                                                "&statusBarHeight=0&android=4.1" + "&SDK=" + Build.VERSION.SDK_INT + parme
                                                + "&url=" + PreferencesUtils.getString(H5BridgeOtherActivity.this, BaseConfigs.STRING_SERVER_URL, Constants.SERVER_URL);

                                    }
                                    if (!TextUtils.isEmpty(parme))
                                        openUrl = openUrl + "&" + parme;
                                    intent.putExtra(Constants.H5_WEB_URL, openUrl);
                                    String sessionId = PreferencesUtils.getString(H5BridgeOtherActivity.this, BaseConfigs.PREF_SESSIONID);
                                    intent.putExtra("sessionId", sessionId);
                                    startActivity(intent);
                                }

                            }

                        }
                    }
                });


        //popWindow用来关闭当前页面，自动返回到上一个
        webview.registerHandler("popWindow", new

                BridgeHandler() {

                    @Override
                    public void handler(String data, CallBackFunction function) {
                        finish();
                    }
                });

        //获取当前app版本号
        webview.registerHandler("getAppVersion", new

                BridgeHandler() {
                    @Override
                    public void handler(String data, CallBackFunction function) {
                        HostJsScope.h5PostLocalCallBack(webview, "0", "", true, "getAppVersion", AppUtils.getVerName(H5BridgeOtherActivity.this), function);
                    }
                });
        //更新app版本
        webview.registerHandler("upgradeApp", new

                BridgeHandler() {
                    @Override
                    public void handler(String data, CallBackFunction function) {
                        Log.e("data", data);
                        Response_upgrade response_upgrade = (Response_upgrade) GsonUtils.json2Obj(data, Response_upgrade.class);
                        if (response_upgrade != null && response_upgrade.getAppVersion() != null) {
                            AppVersion appVersion = response_upgrade.getAppVersion();
                            String downLoadUrl = appVersion.getAddress();
                            showVersionUpdate(appVersion, downLoadUrl);
                        }
                    }
                });
        //检验接口是否存在
        webview.registerHandler("checkApi", new

                BridgeHandler() {
                    @Override
                    public void handler(String data, CallBackFunction function) {
                        JsonObject jsonObject = HostJsScope.Json2JsonObject(data);
                        Response_Base response_base = new Response_Base();
                        String code = "";
                        String msg = "";
                        boolean success;
                        if (jsonObject != null && jsonObject.get("apiName") != null) {
                            String str = jsonObject.get("apiName").getAsString();
                            Log.i("zx", "str:" + str);
                            if (!TextUtils.isEmpty(str) && apiQueue.contains(str)) {
                                //说明接口存在
                                code = "0";
                                msg = "支持该接口";
                                success = true;

                            } else {
                                //接口不存在
                                code = "-1";
                                msg = "接口不存在";
                                success = false;
                            }
                        } else {
                            //data格式有问题
                            code = "-1";
                            msg = "数据格式有问题";
                            success = false;
                        }
                        response_base.setResultObject(null);
                        HostJsScope.h5PostLocalCallBack(webview, code, msg, success, "checkApi", response_base, function);

                    }
                });
        //拨打电话
        webview.registerHandler("dial", new

                DefaultHandler() {
                    @Override
                    public void handler(String data, CallBackFunction function) {
                        if (TextUtils.isEmpty(data))
                            return;
                        JsonObject jsonObject = HostJsScope.Json2JsonObject(data);
                        if (jsonObject != null && jsonObject.get("mobile") != null) {
                            String str = jsonObject.get("mobile").getAsString() + "";
                            Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + str));
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                            Response_Base response_base = new Response_Base();
                            response_base.setCode("0");
                            response_base.setSuccess(true);
                            response_base.setResultObject(null);
                            HostJsScope.h5PostLocalCallBack(webview, "0", "", true, "dial", response_base, function);
                        }

                    }
                });
        //发送http请求
        webview.registerHandler("sendHttpRequest", new

                DefaultHandler() {
                    @Override
                    public void handler(String data, CallBackFunction function) {
                        HostJsScope jsScope = new HostJsScope();
                        jsScope.resultCallBack(webview, "sendHttpRequest", data, function);
                    }
                });
        //切换app到后台
        webview.registerHandler("exitApp", new

                DefaultHandler() {
                    @Override
                    public void handler(String data, CallBackFunction function) {
                        Intent intent = new Intent(Intent.ACTION_MAIN);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.addCategory(Intent.CATEGORY_HOME);
                        startActivity(intent);
                    }
                });
        webview.registerHandler("getUserInfo", new

                DefaultHandler() {
                    @Override
                    public void handler(String data, CallBackFunction function) {
                        //Toast.makeText(H5BridgeOtherActivity.this, data, Toast.LENGTH_SHORT).show();
                        Response_Base response_base = new Response_Base();
                        String code = "0";
                        String msg = "获取用户信息";
                        boolean success = true;
                        UserInfo userInfo = new UserInfo();
                        userInfo.setSessionId(PreferencesUtils.getString(H5BridgeOtherActivity.this, BaseConfigs.PREF_SESSIONID));
                        HostJsScope.h5PostLocalCallBack(webview, code, msg, success, "getUserInfo", userInfo, function);

                    }
                });
        //退出登录
        webview.registerHandler("logout", new

                BridgeHandler() {
                    @Override
                    public void handler(String data, final CallBackFunction function) {
                        H5Subscription.h5LogoutSubscription(new ApiCallback() {
                            @Override
                            public void onSuccess(Response_Base response_baseModel) {
                                PreferencesUtils.putString(H5BridgeOtherActivity.this, BaseConfigs.STRING_MOVEKOUBEI, "0");
                                RxBus.getInstance().send(Events.EVENT_302CODE, "");
                                Intent intent = new Intent(H5BridgeOtherActivity.this, LoginActivity.class);
                                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

                                intent.putExtra("logout", "1");

                                startActivity(intent);
                                Response_Base response_base = new Response_Base();
                                response_base.setCode("0");
                                response_base.setSuccess(true);
                                response_base.setResultObject(null);
                                HostJsScope.h5PostLocalCallBack(webview, "0", "", true, "logout", response_base, function);
                            }

                            @Override
                            public void onNeedLogin(String msg) {
                            }

                            @Override
                            public void onFail(Response_Base response_baseModel) {
                                if (response_baseModel != null) {
                                    String msg = response_baseModel.getMsg();
                                    HostJsScope.h5PostLocalCallBack(webview, TConstant.CODE_FAIL, "失败", true, "logout", "", function);
                                }
                            }
                        });

                    }
                });
        //拍照并裁切接口
        webview.registerHandler("takePicture", new

                BridgeHandler() {
                    @Override
                    public void handler(String data, CallBackFunction function) {
                        LogUtils.d("--- takePicture");

                        Photo photo = (Photo) GsonUtils.json2Obj(data, Photo.class);
                        TakePhoto takePhoto = getTakePhoto();
                        if (photo != null) {
                            Compress compress = photo.getCompress();
                            MaxSize maxSize = photo.getMaxSize();
                            if (compress != null || maxSize != null) {
                                LubanOptions.Builder builder = new LubanOptions.Builder();
                                if (maxSize != null) {
                                    if (!TextUtils.isEmpty(maxSize.getWidth()) && !TextUtils.isEmpty(maxSize.getHeight())) {

                                        builder.setMaxWidth(Integer.parseInt(maxSize.getWidth()))
                                                .setMaxHeight(Integer.parseInt(maxSize.getHeight()));
                                    }
                                }
                                if (compress != null) {
                                    builder.setMaxSize(compress.getSizeLimit() * 1024).setUnit(compress.getUnit());
                                }
                                LubanOptions compressOptions = builder.create();
                                CompressOptions config = CompressOptions.ofLuban(compressOptions);
                                takePhoto.onEnableCompress(config, true);
                            } else {
                                takePhoto.onEnableCompress(null, false);
                            }

                            Crop crop = photo.getCrop();
                            if (crop != null) {
                                CropOptions.Builder cropBuilder = new CropOptions.Builder();
                                CropOptions cropOptions = cropBuilder.setAspectX(crop.getWidthRatio()).setAspectY(crop.getHeightRatio()).setFormat(photo.getFormat()).create();
                                LogUtils.d(" crop one picture with width: " + crop.getWidthRatio() + " height:" + crop.getHeightRatio() + " format:" + photo.getFormat());
                                takePhoto.onPickFromCaptureWithCrop(TImageFiles.getTempFileUri(), cropOptions);
                            } else {
                                takePhoto.onPickFromCapture(TImageFiles.getTempFileUri());
                            }

                        }
                        apiName = "takePicture";
                        takePictureCallBackFunction = function;

                    }
                });
        //选择多图接口 多图不支持裁剪 单图支持裁剪
        webview.registerHandler("selectPicture", new

                BridgeHandler() {

                    @Override
                    public void handler(String data, CallBackFunction function) {
                        File file = new File(Environment.getExternalStorageDirectory(), "/temp/" + System.currentTimeMillis() + ".jpg");
                        if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
                        Uri imageUri = Uri.fromFile(file);
                        Photo photo = (Photo) GsonUtils.json2Obj(data, Photo.class);
                        if (photo != null) {

                            Compress compress = photo.getCompress();
                            MaxSize maxSize = photo.getMaxSize();
                            if (compress != null || maxSize != null) {
                                LubanOptions.Builder builder = new LubanOptions.Builder();
                                if (maxSize != null) {
                                    if (maxSize != null && !TextUtils.isEmpty(maxSize.getWidth()) && !TextUtils.isEmpty(maxSize.getHeight())) {
                                        builder.setMaxWidth(Integer.parseInt(maxSize.getWidth()));
                                        builder.setMaxHeight(Integer.parseInt(maxSize.getHeight()));
                                    }
                                }
                                if (compress != null) {
                                    builder.setMaxSize(compress.getSizeLimit() * 1024).setUnit(compress.getUnit());
                                }
                                LubanOptions compressOptions = builder.create();
                                CompressOptions config = CompressOptions.ofLuban(compressOptions);
                                getTakePhoto().onEnableCompress(config, true);
                            } else {
                                getTakePhoto().onEnableCompress(null, false);
                            }
                            int limit = photo.getMaxNum();
                            if (limit > 1) {
                                Crop crop = photo.getCrop();
                                if (crop != null) {
                                    LogUtils.d(" crop mulitule pictures with width: " + crop.getWidthRatio() + " height:" + crop.getHeightRatio() + " format:" + photo.getFormat());
                                    CropOptions.Builder cropBuilder = new CropOptions.Builder();
                                    CropOptions cropOptions = cropBuilder.setAspectX(crop.getWidthRatio()).setAspectY(crop.getHeightRatio()).setFormat(photo.getFormat()).create();
                                    takePhoto.onPickMultipleWithCrop(limit, cropOptions);
                                } else {
                                    getTakePhoto().onPickMultiple(limit);
                                }
                            } else {
                                Crop crop = photo.getCrop();
                                if (crop != null) {
                                    LogUtils.d(" crop one picture with width: " + crop.getWidthRatio() + " height:" + crop.getHeightRatio() + " format:" + photo.getFormat());
                                    CropOptions.Builder cropBuilder = new CropOptions.Builder();
                                    CropOptions cropOptions = cropBuilder.setOutputX(crop.getWidthRatio()).setOutputY(crop.getHeightRatio()).setFormat(photo.getFormat()).create();
                                    takePhoto.onPickFromGalleryWithCrop(imageUri, cropOptions);
                                } else {
                                    takePhoto.onPickFromGallery();
                                }
                            }
                        }
                        apiName = "selectPicture";
                        selectPictureCallBackFunction = function;
                    }
                });

        //保存图片
        webview.registerHandler("savePicture", new

                BridgeHandler() {
                    @Override
                    public void handler(String data, CallBackFunction function) {

                        if (TextUtils.isEmpty(data))
                            return;
                        JsonObject jsonObject = HostJsScope.Json2JsonObject(data);
                        if (jsonObject != null && jsonObject.get("url") != null) {
                            String url = jsonObject.get("url").getAsString() + "";
                            savePictureCallBackFunction = function;
                            if (!TextUtils.isEmpty(url)) {
                                saveImage(url);
                            }

                        }
                    }

                });

        webview.registerHandler("scan", new

                BridgeHandler() {
                    @Override
                    public void handler(final String data, final CallBackFunction function) {
                        LogUtils.d("--- H5bridge other scan");
                        if (TextUtils.isEmpty(data))
                            return;
                        scanCallBackFunction = function;
                        XXPermissions.with(H5BridgeOtherActivity.this).permission(Permission.CAMERA
                        ).request(new OnPermission() {
                            @Override
                            public void hasPermission(List<String> granted, boolean isAll) {
                                dismissTopDialog();
                                Intent intent = new Intent(H5BridgeOtherActivity.this, ScanActivity.class);
                                JsonObject jsonObject = HostJsScope.Json2JsonObject(data);
                                if (jsonObject != null && jsonObject.get("title") != null) {
                                    String title = jsonObject.get("title").getAsString() + "";
                                    intent.putExtra("title", title);
                                }
                                if (jsonObject != null && jsonObject.get("text") != null) {
                                    String title = jsonObject.get("text").getAsString() + "";
                                    intent.putExtra("text", title);
                                }
                                intent.putExtra("from", "H5BridgeOtherActivity");
                                startActivityForResult(intent, 5);

                            }

                            @Override
                            public void noPermission(List<String> denied, boolean quick) {
                                dismissTopDialog();
                                HostJsScope.h5PostLocalCallBack(webview, "11", "未开启摄像头权限", false, "scan", null, scanCallBackFunction);

                            }
                        });
                        if (!XXPermissions.isHasPermission(H5BridgeOtherActivity.this, Permission.CAMERA)) {
                            showTopDialog("为了您能正常使用【扫码】功能，需向您申请相机权限。如果不允许，您将无法使用扫码功能。");
                        }
                    }


                });

        webview.registerHandler("authV2", new

                BridgeHandler() {
                    @Override
                    public void handler(String data, CallBackFunction function) {
                        authV2CallBackFunction = function;
                        getSign();
                    }
                });
        webview.registerHandler("tradePay", new

                BridgeHandler() {
                    @Override
                    public void handler(String data, CallBackFunction function) {
                        payV2CallBackFunction = function;
                        JsonObject jsonObject = HostJsScope.Json2JsonObject(data);
                        if (jsonObject != null && jsonObject.get("payType") != null) {
                            String payType = jsonObject.get("payType").getAsString() + "";

                            String orderInfo = jsonObject.get("orderInfo").getAsString() + "";

                            if ("alipay".equals(payType)) {

                                payV2(orderInfo);
                            }

                        }

                    }
                });


        //图片缩放预览
        webview.registerHandler("viewPicture", new
                BridgeHandler() {
                    @Override
                    public void handler(String data, CallBackFunction function) {

                        Image image = (Image) GsonUtils.json2Obj(data, Image.class);
                        if (image != null) {
                            Intent intent = new Intent(H5BridgeOtherActivity.this, PhotoViewActivity.class);
                            intent.putExtra("currentIndex", image.getCurrent());

                            intent.putStringArrayListExtra("files", image.getFiles());
                            startActivity(intent);
                            apiName = "viewPicture";
                            photoviewCallBackFunction = function;
                        }
                    }
                });
        //上传文件及参数
        webview.registerHandler("uploadPicture", new
                BridgeHandler() {
                    @Override
                    public void handler(String data, final CallBackFunction function) {
                        LogUtils.d("upload data==== " + data);
                        final Upload upload = (Upload) GsonUtils.json2Obj(data, Upload.class);
                        if (upload != null) {
                            if (!TextUtils.isEmpty(upload.getUrl())) {
                                uploadPictureCallBackFunction = function;
                                XXPermissions.with(H5BridgeOtherActivity.this).permission(Permission.WRITE_EXTERNAL_STORAGE,
                                        Permission.READ_EXTERNAL_STORAGE).request(new OnPermission() {

                                    @Override
                                    public void hasPermission(List<String> granted, boolean isAll) {
                                        if (isAll) {
                                            dismissTopDialog();
                                            TUtils.uploadPictures(webview, upload.getUrl(), upload.getFile(), upload.getData());
                                            apiName = "uploadPicture";

                                        }
                                    }

                                    @Override
                                    public void noPermission(List<String> denied, boolean quick) {
                                        dismissTopDialog();
                                        HostJsScope.h5PostLocalCallBack(webview, "-1", "未开启存储权限", false, "uploadPicture", "", uploadPictureCallBackFunction);
                                        if (uploadPictureCallBackFunction != null) {
                                            uploadPictureCallBackFunction = null;
                                        }
                                    }
                                });
                                if (!XXPermissions.isHasPermission(H5BridgeOtherActivity.this, Permission.WRITE_EXTERNAL_STORAGE, Permission.READ_EXTERNAL_STORAGE)) {
                                    showTopDialog("为了您能正常上传身份证，完成身份认证等功能，，需向您申请媒体文件存储权限。如果不允许，您将无法存储和取用相册图片。");
                                }

                            }
                        }
                    }
                });

    }

    //拍照
    private void takePhoto() {
        File fileUri = new File(Environment.getExternalStorageDirectory().getPath() + "/" + SystemClock.currentThreadTimeMillis() + ".jpg");
        imageUri = Uri.fromFile(fileUri);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            imageUri = FileProvider.getUriForFile(H5BridgeOtherActivity.this, getPackageName() + ".provider", fileUri);//通过FileProvider创建一个content类型的Uri
        }
        PhotoUtils.takePicture(H5BridgeOtherActivity.this, imageUri, PHOTO_REQUEST);
    }

    /**
     * 录像
     */
    private void recordVideo() {
        Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
        //限制时长
        intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 30);
        //开启摄像机
        startActivityForResult(intent, VIDEO_REQUEST);
    }

    private void saveImage(final String imgUrl) {
        XXPermissions.with(this).permission(Permission.WRITE_EXTERNAL_STORAGE,
                Permission.READ_EXTERNAL_STORAGE).request(new OnPermission() {

            @Override
            public void hasPermission(List<String> granted, boolean isAll) {
                if (isAll) {
                    dismissTopDialog();
                    new WriteString(imgUrl).start();
                }
            }

            @Override
            public void noPermission(List<String> denied, boolean quick) {
                dismissTopDialog();
                Response_Base response_base = new Response_Base();
                response_base.setResultObject(null);
                response_base.setCode("-1");
                response_base.setSuccess(false);
                HostJsScope.h5PostLocalCallBack(webview, "-1", "未开启存储权限", false, "savePicture", response_base, savePictureCallBackFunction);

            }
        });
        if (!XXPermissions.isHasPermission(H5BridgeOtherActivity.this, Permission.WRITE_EXTERNAL_STORAGE,
                Permission.READ_EXTERNAL_STORAGE)) {
            showTopDialog("为了您能正常使用【保存图片】等功能，，需向您申请媒体文件存储权限。如果不允许，您将无法存储和取用相册图片。");
        }
    }

    private class WriteString extends Thread {

        private String url;

        public WriteString(String url) {
            this.url = url;
        }

        @Override
        public void run() {
            super.run();
            //干你需要做的操作
            String fileUrl = FileUtils.writeFile(url);
            Response_Base response_base = new Response_Base();
            response_base.setResultObject(null);
            if (!TextUtils.isEmpty(fileUrl)) {
                response_base.setCode("0");
                response_base.setSuccess(true);
                HostJsScope.h5PostLocalCallBack(webview, "0", "", true, "savePicture", response_base, savePictureCallBackFunction);

                Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                Uri uri = Uri.fromFile(new File(fileUrl));
                intent.setData(uri);
                sendBroadcast(intent);
            } else {
                response_base.setCode("-1");
                response_base.setSuccess(false);
                HostJsScope.h5PostLocalCallBack(webview, "-1", "", false, "savePicture", response_base, savePictureCallBackFunction);
            }
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        getTakePhoto().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent data) {
        if (requestCode != PHOTO_REQUEST || mUploadCallbackAboveL == null) {
            return;
        }
        Uri[] results = null;
        if (resultCode == Activity.RESULT_OK) {
            if (data == null) {
                results = new Uri[]{imageUri};
            } else {
                String dataString = data.getDataString();
                ClipData clipData = data.getClipData();
                if (clipData != null) {
                    results = new Uri[clipData.getItemCount()];
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        ClipData.Item item = clipData.getItemAt(i);
                        results[i] = item.getUri();
                    }
                }

                if (dataString != null) {
                    results = new Uri[]{Uri.parse(dataString)};
                }

            }
        }
        mUploadCallbackAboveL.onReceiveValue(results);
        mUploadCallbackAboveL = null;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == PHOTO_REQUEST) {
            if (null == mUploadMessage && null == mUploadCallbackAboveL) {
                return;
            }
            Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
            if (mUploadCallbackAboveL != null) {
                onActivityResultAboveL(requestCode, resultCode, data);
            } else if (mUploadMessage != null) {
                mUploadMessage.onReceiveValue(result);
                mUploadMessage = null;
            }
        } else if (requestCode == VIDEO_REQUEST) {
            if (null == mUploadMessage && null == mUploadCallbackAboveL) {
                return;
            }

            Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
            if (mUploadCallbackAboveL != null) {
                if (resultCode == RESULT_OK) {
                    mUploadCallbackAboveL.onReceiveValue(new Uri[]{result});
                    mUploadCallbackAboveL = null;
                } else {
                    mUploadCallbackAboveL.onReceiveValue(new Uri[]{});
                    mUploadCallbackAboveL = null;
                }

            } else if (mUploadMessage != null) {
                if (resultCode == RESULT_OK) {
                    mUploadMessage.onReceiveValue(result);
                    mUploadMessage = null;
                } else {
                    mUploadMessage.onReceiveValue(Uri.EMPTY);
                    mUploadMessage = null;
                }

            }
        }


        if (requestCode == 5 && resultCode == 5) {
            if (data != null) {
                String code = data.getStringExtra("code");
                if (!TextUtils.isEmpty(code)) {
                    HostJsScope.h5PostLocalCallBack(webview, "0", "", true, "scan", code, scanCallBackFunction);
                } else {
                    if (!TextUtils.isEmpty(data.getStringExtra("cancel"))) {
                        HostJsScope.h5PostLocalCallBack(webview, "10", "", false, "scan", null, scanCallBackFunction);
                    } else {
                        HostJsScope.h5PostLocalCallBack(webview, "11", "", false, "scan", null, scanCallBackFunction);
                    }
                }
            }
        } else {
            getTakePhoto().onActivityResult(requestCode, resultCode, data);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(this, type, invokeParam, this);
    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }

    @Override
    public void takeSuccess(TResult result) {
        if (result != null) {
            //拍照裁剪图片返回数据
            if (takePictureCallBackFunction != null) {
                TImage image = result.getImage();
                if (image != null) {

                    String imagePath = image.getCompressPath();
                    if (TextUtils.isEmpty(imagePath)) {
                        imagePath = image.getOriginalPath();
                    }


                    if (!TextUtils.isEmpty(imagePath)) {
                        HostJsScope.h5PostLocalCallBack(webview, TConstant.CODE_SUCCESS, "成功", true, apiName, "file://" + imagePath, takePictureCallBackFunction);
                        takePictureCallBackFunction = null;
                    }
                }
            }

            //选择图片裁剪返回数据
            if (selectPictureCallBackFunction != null) {
                List<TImage> images = result.getImages();
                List<String> imagePaths = new ArrayList<>();
                if (images != null && images.size() > 0) {
                    for (TImage tImage : images) {
                        if (tImage != null) {
                            String imagePath = tImage.getCompressPath();
                            if (TextUtils.isEmpty(imagePath)) {
                                imagePath = tImage.getOriginalPath();
                            }


                            imagePaths.add("file://" + imagePath);
                            LogUtils.d(" images ==== " + imagePath);
                        }
                    }
                    if (imagePaths != null && imagePaths.size() > 0) {
                        HostJsScope.h5PostLocalCallBack(webview, TConstant.CODE_SUCCESS, "成功", true, apiName, imagePaths, selectPictureCallBackFunction);
                        selectPictureCallBackFunction = null;
                    }
                }

            }
        }
    }

    @Override
    public void takeFail(TResult result, String msg) {
        if (takePictureCallBackFunction != null) {
            HostJsScope.h5PostLocalCallBack(webview, TConstant.CODE_FAIL, "失败", true, apiName, "", takePictureCallBackFunction);
            takePictureCallBackFunction = null;
        }
        if (selectPictureCallBackFunction != null) {
            HostJsScope.h5PostLocalCallBack(webview, TConstant.CODE_FAIL, "失败", true, apiName, "", selectPictureCallBackFunction);
            selectPictureCallBackFunction = null;
        }

    }

    @Override
    public void takeCancel() {

        if (takePictureCallBackFunction != null) {
            takePictureCallBackFunction = null;
        }
        if (selectPictureCallBackFunction != null) {
            selectPictureCallBackFunction = null;
        }
    }

    class MyWebChromeClient extends WebChromeClient {


        @Override
        public void onProgressChanged(WebView view, int newProgress) {
        }


        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            String substring = "404";
            int index = title.indexOf('#');  // 找到#的位置
            if (index != -1) {
                String substringBeforeHash = title.substring(0, index);
                if (substringBeforeHash.contains(substring)) {
                    showErrorPage();
                }
            }
        }

        // For Android 3.0-
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            Log.d(TAG, "3.0- openFileChoose(ValueCallback<Uri> uploadMsg)");
            mUploadMessage = uploadMsg;
            if (videoFlag) {
                recordVideo();
            } else {
                takePhoto();
            }

        }

        // For Android 3.0+
        public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
            Log.d(TAG, "openFileChoose( 3.0+ValueCallback uploadMsg, String acceptType )");
            mUploadMessage = uploadMsg;
            if (videoFlag) {
                recordVideo();
            } else {
                takePhoto();
            }
        }

        //For Android 4.1
        @Override
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            Log.d(TAG, "4.1 openFileChoose(ValueCallback<Uri> uploadMsg, String acceptType, String capture)");
            mUploadMessage = uploadMsg;
            if (acceptType.contains("video")) {
                recordVideo();
            } else {
                Log.d(TAG, "takePhoto");
                takePhoto();
            }
        }

        // For Android 5.0+
        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
            Log.d(TAG, "5.0+ onShowFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture)");
            mUploadCallbackAboveL = filePathCallback;
            return super.onShowFileChooser(webView, filePathCallback, fileChooserParams);

        }
    }

    /**
     * 自定义的WebViewClient
     */
    class MyWebViewClient extends BridgeWebViewClient {

        public MyWebViewClient(BridgeWebView webView) {
            super(webView);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            dismissLoading();
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (!isErrorPage) {
                hideErrorPage();
            }
            view.loadUrl("javascript:window.YzJSBridge = window.WebViewJavascriptBridge;window.YzJSBridge.call = window.YzJSBridge.callHandler;");
            view.loadUrl("javascript:AppUtil.trigger(AppUtil.EVENTS.READY_EVENT);");
            view.loadUrl("javascript:readyFunc();");
            loading_layout.setVisibility(View.GONE);
            dismissLoading();

        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            Log.i("zx", failingUrl + "onReceivedError==" + description + "     errorCode" + errorCode);
            showErrorPage();
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Log.i("lkf", " shouldOverrideUrlLoading----" + url);

            if (url.startsWith("taobao://")) {
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(intent);
                return true;
            }

            if (!TextUtils.isEmpty(url)) {
                videoFlag = url.contains("vedio");
            }
            if (url.trim().startsWith("tel")) {//特殊情况tel，调用系统的拨号软件拨号【<a href="tel:1111111111">1111111111</a>】
                Intent i = new Intent(Intent.ACTION_VIEW);
                i.setData(Uri.parse(url));
                startActivity(i);
            }

            if (url.equals(backUrl)) {
                H5BridgeOtherActivity.this.finish();
            }
            return super.shouldOverrideUrlLoading(view, url);

        }

    }

    private boolean isErrorPage;//默认false 说明不是错误页面

    public void showErrorPage() {
        errorLayout.setVisibility(View.VISIBLE);
        webview.setVisibility(View.GONE);
        isErrorPage = true;
    }

    public void hideErrorPage() {
        errorLayout.setVisibility(View.GONE);
        webview.setVisibility(View.VISIBLE);
    }

    public void payV2(final String orderInfo) {
        if (!TextUtils.isEmpty(orderInfo)) {
            Runnable payRunnable = new Runnable() {

                @Override
                public void run() {
                    PayTask alipay = new PayTask(H5BridgeOtherActivity.this);
                    Map<String, String> result = alipay.payV2(orderInfo, true);
                    Log.i("msp", result.toString());

                    Message msg = new Message();
                    msg.what = SDK_PAY_FLAG;
                    msg.obj = result;
                    mHandler.sendMessage(msg);
                }
            };

            Thread payThread = new Thread(payRunnable);
            payThread.start();
        } else {
            HostJsScope.h5PostLocalCallBack(webview, TConstant.CODE_FAIL, "未获取到orderInfo", true,
                    "tradePay", "", payV2CallBackFunction);
            if (payV2CallBackFunction != null) {
                payV2CallBackFunction = null;
            }
        }

    }

    //获取sign 并且支付宝登录
    private void getSign() {
        showLoading("正在加载...");
        NetWorkRequset.doJoinLogin(new MySubscriber() {
            @Override
            public void onSuccess(Response_Base response_baseModel) {
                dismissLoading();
                String sign = (String) response_baseModel.getResultObject();
                if (!TextUtils.isEmpty(sign)) {
                    authV2(sign);
                } else {
                    HostJsScope.h5PostLocalCallBack(webview, TConstant.CODE_FAIL, "未获取到sign", true, "authV2", "", authV2CallBackFunction);
                    if (authV2CallBackFunction != null) {
                        authV2CallBackFunction = null;
                    }
                }
            }

            @Override
            public void onNeedLogin(String msg) {
                dismissLoading();

            }

            @Override
            public void onCompleted() {
                super.onCompleted();
                dismissLoading();

            }

            @Override
            public void onFail(Response_Base response_baseModel) {
                dismissLoading();
                if (!TextUtils.isEmpty(response_baseModel.getMsg())) {
                    HostJsScope.h5PostLocalCallBack(webview, TConstant.CODE_FAIL, response_baseModel.getMsg(), true, "authV2", "", authV2CallBackFunction);
                    if (authV2CallBackFunction != null) {
                        authV2CallBackFunction = null;
                    }
                }
            }
        });
    }

    /**
     * 支付宝账户授权业务
     */
    private void authV2(final String sign) {
        Runnable authRunnable = new Runnable() {

            @Override
            public void run() {
                // 构造AuthTask 对象
                AuthTask authTask = new AuthTask(H5BridgeOtherActivity.this);
                // 调用授权接口，获取授权结果
                Map<String, String> result = authTask.authV2(sign, true);

                Message msg = new Message();
                msg.what = 1;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread authThread = new Thread(authRunnable);
        authThread.start();
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    //对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();

                    HostJsScope.h5PostLocalCallBack(webview, TConstant.CODE_SUCCESS, "", true,
                            "tradePay", payResult, payV2CallBackFunction);
                    if (payV2CallBackFunction != null) {
                        payV2CallBackFunction = null;
                    }
                    break;
                }
                case 1: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();
                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        HostJsScope.h5PostLocalCallBack(webview, TConstant.CODE_SUCCESS, "", true, "authV2", authResult.getUserId(), authV2CallBackFunction);
                    } else {
                        // 其他状态值则为授权失败
                        HostJsScope.h5PostLocalCallBack(webview, TConstant.CODE_FAIL, "授权失败", true, "authV2", "", authV2CallBackFunction);
                    }
                    if (authV2CallBackFunction != null) {
                        authV2CallBackFunction = null;
                    }
                    break;
                }
                default:
                    break;
            }
        }
    };

    public void showVersionUpdate(AppVersion appVersion, final String url) {

        Intent intentDown = new Intent(this, DownLoadDialogActivity.class);
        intentDown.putExtra("url", url);
        intentDown.putExtra("autoLogin", "H5Bridge");
        intentDown.putExtra("appVersion", appVersion);
        startActivity(intentDown);

    }

    //未授权权限弹出对话框
    public void permissionDialog(String msg) {
        final PublicDialog permission = new PublicDialog(H5BridgeOtherActivity.this);
        permission.setTitle("请开启相关权限");
        permission.setMessage(msg);
        permission.setRightBtn("去设置", new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                XXPermissions.gotoPermissionSettings(H5BridgeOtherActivity.this);
                permission.dismiss();
            }
        });
        permission.setLeftBtn("取消", new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                permission.dismiss();
                H5BridgeOtherActivity.this.finish();
            }
        });
        permission.setCancelable(false);
        permission.show();

    }

    private TopDialog topDialog = null;

    public void showTopDialog(String content) {
        topDialog = new TopDialog(H5BridgeOtherActivity.this);
        topDialog.setContent(content);
        topDialog.show();
    }

    private void dismissTopDialog() {
        if (topDialog != null) {
            topDialog.dismiss();
            topDialog = null;
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (smartConfig != null) {
            smartConfig.stop();
        }
        if (webview != null) {
            webview.setWebViewClient(null);
            webview.setWebChromeClient(null);
            webview.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            webview.clearHistory();
            webview.destroy();
            webview = null;

        }
        if (myRecriver != null) {
            unregisterReceiver(myRecriver);
        }
    }
}
